/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.univali.compiladores.compilador.gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import br.univali.compiladores.compilador.EG1;
import br.univali.compiladores.compilador.ParseException;
import br.univali.compiladores.compilador.Token;
import br.univali.compiladores.maquinavirtual.InstrucoesFrame;

/**
 *
 * @author Jeferson
 */
public class TelaPrincipal2 extends javax.swing.JFrame {

    private boolean foiAlterado;
    private static final String EXTENSAO_DE_TEXTO = "txt";
    private static final String COMPILADOR_TITULO = "Compilador";
    private File arquivoAtual;
    private JFileChooser fileChooser = new JFileChooser();
    private EG1 eg;
    private InstrucoesFrame instrucoesFrame;
    /**
     * Creates new form TelaPrincipal2
     */
    public TelaPrincipal2() {
        initComponents();
        
        inputArea.addKeyListener(new KeyListener() {

                @Override
                public void keyTyped(KeyEvent arg0) {
                        foiAlterado = true;
                }

                @Override
                public void keyPressed(KeyEvent e) {
                }

                @Override
                public void keyReleased(KeyEvent e) {
                }
        });
        
        inputArea.addCaretListener(new CaretListener() {

            @Override
            public void caretUpdate(CaretEvent e) {
                entradaCaretUpdate(e);
            }
        });
    }
    
    private void entradaCaretUpdate(javax.swing.event.CaretEvent evt) {                                    
        try {
            this.linha.setText(inputArea.getLineOfOffset(inputArea.getSelectionStart()) + 1 + "");
            this.coluna.setText(inputArea.getSelectionStart() - inputArea.getLineStartOffset(inputArea.getLineOfOffset(inputArea.getSelectionStart())) + 1 + "");
        } catch (Exception ex) {
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem1 = new javax.swing.JMenuItem();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        outputArea = new javax.swing.JTextPane();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        inputArea = new javax.swing.JTextArea();
        botaoCompilar = new javax.swing.JButton();
        botaoExecutar = new javax.swing.JButton();
        linha = new javax.swing.JLabel();
        coluna = new javax.swing.JLabel();
        botaoNovo = new javax.swing.JButton();
        botaoAbrir = new javax.swing.JButton();
        botaoSalvar = new javax.swing.JButton();
        botaoRecortar = new javax.swing.JButton();
        botaoCopiar = new javax.swing.JButton();
        botaoColar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        itemDeMenuNovo = new javax.swing.JMenuItem();
        itemDeMenuAbrir = new javax.swing.JMenuItem();
        itemDeMenuSalvar = new javax.swing.JMenuItem();
        itemDeMenuSalvarComo = new javax.swing.JMenuItem();
        itemDeMenuSair = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        itemDeMenuCopiar = new javax.swing.JMenuItem();
        itemDeMenuColar = new javax.swing.JMenuItem();
        itemDeMenuRecortar = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        itemDeMenuCompilar = new javax.swing.JMenuItem();
        itemDeMenuExecutar = new javax.swing.JMenuItem();

        jMenuItem1.setText("Salvar");

        jButton2.setText("jButton2");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Compilador");

        jScrollPane1.setViewportView(outputArea);

        jLabel1.setText("Posição: ");

        inputArea.setColumns(20);
        inputArea.setRows(5);
        jScrollPane2.setViewportView(inputArea);

        botaoCompilar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/compile-icon.png"))); // NOI18N
        botaoCompilar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCompilarActionPerformed(evt);
            }
        });

        botaoExecutar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/Play-icon.png"))); // NOI18N
        botaoExecutar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        botaoExecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoExecutarActionPerformed(evt);
            }
        });

        linha.setText("0");

        coluna.setText("0");

        botaoNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/novo.png"))); // NOI18N
        botaoNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoNovoActionPerformed(evt);
            }
        });

        botaoAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/abrir.png"))); // NOI18N
        botaoAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAbrirActionPerformed(evt);
            }
        });

        botaoSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/salvar.png"))); // NOI18N
        botaoSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoSalvarActionPerformed(evt);
            }
        });

        botaoRecortar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/recortar.png"))); // NOI18N
        botaoRecortar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoRecortarActionPerformed(evt);
            }
        });

        botaoCopiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/copiar.png"))); // NOI18N
        botaoCopiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCopiarActionPerformed(evt);
            }
        });

        botaoColar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/colar.png"))); // NOI18N
        botaoColar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoColarActionPerformed(evt);
            }
        });

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jMenu1.setText("Arquivo");

        itemDeMenuNovo.setText("Novo");
        itemDeMenuNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuNovoActionPerformed(evt);
            }
        });
        jMenu1.add(itemDeMenuNovo);

        itemDeMenuAbrir.setText("Abrir");
        itemDeMenuAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuAbrirActionPerformed(evt);
            }
        });
        jMenu1.add(itemDeMenuAbrir);

        itemDeMenuSalvar.setText("Salvar");
        itemDeMenuSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuSalvarActionPerformed(evt);
            }
        });
        jMenu1.add(itemDeMenuSalvar);

        itemDeMenuSalvarComo.setText("Salvar Como");
        itemDeMenuSalvarComo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuSalvarComoActionPerformed(evt);
            }
        });
        jMenu1.add(itemDeMenuSalvarComo);

        itemDeMenuSair.setText("Sair");
        itemDeMenuSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuSairActionPerformed(evt);
            }
        });
        jMenu1.add(itemDeMenuSair);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edicao");

        itemDeMenuCopiar.setText("Copiar");
        itemDeMenuCopiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuCopiarActionPerformed(evt);
            }
        });
        jMenu2.add(itemDeMenuCopiar);

        itemDeMenuColar.setText("Colar");
        itemDeMenuColar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuColarActionPerformed(evt);
            }
        });
        jMenu2.add(itemDeMenuColar);

        itemDeMenuRecortar.setText("Recortar");
        itemDeMenuRecortar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuRecortarActionPerformed(evt);
            }
        });
        jMenu2.add(itemDeMenuRecortar);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Compilacao");

        itemDeMenuCompilar.setText("Compilar");
        itemDeMenuCompilar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuCompilarActionPerformed(evt);
            }
        });
        jMenu3.add(itemDeMenuCompilar);

        itemDeMenuExecutar.setText("Executar");
        itemDeMenuExecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuExecutarActionPerformed(evt);
            }
        });
        jMenu3.add(itemDeMenuExecutar);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(linha)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(coluna))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(botaoNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoRecortar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoCopiar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoColar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoCompilar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botaoExecutar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 277, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(botaoCompilar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botaoExecutar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(botaoNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(botaoAbrir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(botaoSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(botaoCopiar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(botaoColar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botaoRecortar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jSeparator2))
                .addGap(20, 20, 20)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(linha)
                    .addComponent(coluna)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void itemDeMenuNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuNovoActionPerformed
        novoArquivo();
    }//GEN-LAST:event_itemDeMenuNovoActionPerformed

    private void itemDeMenuAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuAbrirActionPerformed
        novoArquivo();
        int resultado = fileChooser.showOpenDialog(null);
        
        if (resultado == JFileChooser.APPROVE_OPTION) {
        	arquivoAtual = fileChooser.getSelectedFile();
                File f = null;
                try {
                    f = new File(arquivoAtual.getCanonicalPath());
                } catch (IOException ex) {
                    Logger.getLogger(TelaPrincipal2.class.getName()).log(Level.SEVERE, null, ex);
                }

                // Set the current directory
                fileChooser.setCurrentDirectory(f);
        	alterarInterfaceParaArquivoAtual();
        }
    }//GEN-LAST:event_itemDeMenuAbrirActionPerformed

    private void itemDeMenuSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuSalvarActionPerformed
        if (arquivoAtual != null) {
            salvarArquivo(arquivoAtual);
        } else {
            salvarNoDisco();
        }
    }//GEN-LAST:event_itemDeMenuSalvarActionPerformed

    private void itemDeMenuSalvarComoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuSalvarComoActionPerformed
        salvarNoDisco();
    }//GEN-LAST:event_itemDeMenuSalvarComoActionPerformed

    private void itemDeMenuSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuSairActionPerformed
        fecharAplicacao();
    }//GEN-LAST:event_itemDeMenuSairActionPerformed

    private void itemDeMenuCopiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuCopiarActionPerformed
        inputArea.copy();
    }//GEN-LAST:event_itemDeMenuCopiarActionPerformed

    private void itemDeMenuColarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuColarActionPerformed
        inputArea.paste();
    }//GEN-LAST:event_itemDeMenuColarActionPerformed

    private void itemDeMenuRecortarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuRecortarActionPerformed
        inputArea.cut();
    }//GEN-LAST:event_itemDeMenuRecortarActionPerformed

    private void itemDeMenuCompilarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuCompilarActionPerformed
    	try {
            eg = new EG1(new ByteArrayInputStream(inputArea.getText().getBytes()));
            eg.program();
            if ( eg.token_source.foundLexError() != 0 ){ // verifica se houve erro l�xico
                    outputArea.setText(eg.token_source.foundLexError() + " Erro(s) lexico(s) encontrado(s)\n" + eg.token_source.errors + "\n\nCompilação falhou!");

                    if(this.instrucoesFrame!= null)
                    	this.instrucoesFrame.dispose();
            }
            else{
                    StringBuffer buffer = new StringBuffer();
                    
                    //buffer.append("*INICIANDO ANALISE SINTATICA*\n");
                    eg = new EG1(new ByteArrayInputStream(inputArea.getText().getBytes()));
                    
                    buffer.append(this.analisadorSintatico());
                    
                    outputArea.setText(buffer.toString());
            }
        } catch (Exception e) {
        	outputArea.setText(eg.token_source.foundLexError() + " Erro(s) lexico(s) encontrado(s)\n" + eg.token_source.errors + "\n\nCompilação falhou!");

        }
    	

    }//GEN-LAST:event_itemDeMenuCompilarActionPerformed

    private void itemDeMenuExecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeMenuExecutarActionPerformed
        MaquinaVirtualFrame frame = new MaquinaVirtualFrame(instrucoesFrame.getInstrucoes());
		frame.setVisible(true);

    	
    }//GEN-LAST:event_itemDeMenuExecutarActionPerformed

    private void botaoCompilarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCompilarActionPerformed
        itemDeMenuCompilarActionPerformed(evt);
    }//GEN-LAST:event_botaoCompilarActionPerformed

    private void botaoExecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoExecutarActionPerformed
        itemDeMenuExecutarActionPerformed(evt);
    }//GEN-LAST:event_botaoExecutarActionPerformed

    private void botaoNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoNovoActionPerformed
        itemDeMenuNovoActionPerformed(evt);
    }//GEN-LAST:event_botaoNovoActionPerformed

    private void botaoAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAbrirActionPerformed
        itemDeMenuAbrirActionPerformed(evt);
    }//GEN-LAST:event_botaoAbrirActionPerformed

    private void botaoSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSalvarActionPerformed
        itemDeMenuSalvarActionPerformed(evt);
    }//GEN-LAST:event_botaoSalvarActionPerformed

    private void botaoRecortarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoRecortarActionPerformed
        itemDeMenuRecortarActionPerformed(evt);
    }//GEN-LAST:event_botaoRecortarActionPerformed

    private void botaoCopiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCopiarActionPerformed
        itemDeMenuCopiarActionPerformed(evt);
    }//GEN-LAST:event_botaoCopiarActionPerformed

    private void botaoColarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoColarActionPerformed
        itemDeMenuColarActionPerformed(evt);
    }//GEN-LAST:event_botaoColarActionPerformed

    private void limparCompilador() {
        arquivoAtual = null;
        setTitle(COMPILADOR_TITULO);
        limparInputArea();
        limparOutputArea();
        foiAlterado = false;
    }
    
    private void limparInputArea() {
            inputArea.setText("");
    }

    private void limparOutputArea() {
            outputArea.setText("");
    }
    
    private void novoArquivo() {
    	if (foiAlterado) {
            int resultado = verificaSeUsuarioDesejaSalvarArquivo();

            if (resultado == JOptionPane.YES_OPTION) {
                if (arquivoAtual == null) {
                    salvarNovoArquivoAtual();
                } else {
                    salvarArquivo(arquivoAtual);
                }

                limparCompilador();
            } else if (resultado == JOptionPane.NO_OPTION) {
                limparCompilador();
            }
        } else {
            limparCompilador();
        }
    }
    
    private void fecharAplicacao() {
        if (foiAlterado) {
                int resultado = verificaSeUsuarioDesejaSalvarArquivo();

                if (resultado == JOptionPane.YES_OPTION) {
                        salvarNovoArquivoAtual();
                        dispose();
                } else if (resultado == JOptionPane.NO_OPTION) {
                        dispose();
                }
        } else {
                dispose();
        }
    }
    
    private int verificaSeUsuarioDesejaSalvarArquivo() {
        return JOptionPane.showConfirmDialog(null, "Você deseja salvar o arquivo?", "Salvar", JOptionPane.YES_NO_CANCEL_OPTION);
    }
    
    private void salvarNovoArquivoAtual() {
        if (arquivoAtual != null) {
                salvarArquivo(arquivoAtual);
        } else {
                salvarNoDisco();
        }
    }
    
    private String getArquivoSemExtensao(String nomeDoArquivo) {
        return FilenameUtils.getBaseName(nomeDoArquivo);
    }
    
    private String getExtensaoDoNomeDoArquivo(String nomeDoArquivo) {
        String extensao = FilenameUtils.getExtension(nomeDoArquivo);

        if (extensao == null || extensao.isEmpty()) {
                return EXTENSAO_DE_TEXTO;
        }

        return extensao;
    }
    
    private boolean desejaSobrescreverArquivo() {
        return JOptionPane.showConfirmDialog(
                        null, 
                        "Deseja sobrescrever o arquivo?", 
                        "Sobrescrita de arquivo", 
                        JOptionPane.YES_NO_OPTION
                ) == JOptionPane.YES_OPTION;
    }
    
    private void salvarNoDisco() {
            boolean EhValido = false;

            while (!EhValido) {
                String texto = JOptionPane.showInputDialog("Digite o nome do arquivo: ");
                if (texto == null) break;
                
                String arquivo = getArquivoSemExtensao(texto) + "." + getExtensaoDoNomeDoArquivo(texto);

                File arquivoNovo = new File(arquivo);

                if (arquivoNovo.exists() && desejaSobrescreverArquivo()) {
                        EhValido = true;
                } else if (!arquivoNovo.exists()) {
                        EhValido = true;
                }

                if (EhValido) {
                        salvarArquivo(arquivoNovo);
                }
            }
    }
    
    private void salvarArquivo(File arquivo) {
        try {
                FileUtils.write(arquivo, inputArea.getText());
        } catch (IOException e) {
                e.printStackTrace();
        }

        arquivoAtual = arquivo;
        foiAlterado = false;
        alterarInterfaceParaArquivoAtual();
        exibirMensagemDeArquivoSalvo();
    }
    
    private void exibirMensagemDeArquivoSalvo() {
            JOptionPane.showMessageDialog(null, "Arquivo Salvo.");
    }
    
    private void alterarInterfaceParaArquivoAtual() {
        String textoDoArquivo = obterTextoDoArquivo(arquivoAtual);
        inputArea.setText(textoDoArquivo);
        
        setTitle(COMPILADOR_TITULO + " - " + arquivoAtual.getName());
    }
    
    private String obterTextoDoArquivo(File arquivo) {
    	String texto = null;
    	try {
    		texto = FileUtils.readFileToString(arquivoAtual);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
    	
    	return texto;
     }
    
    
    
    
    
    
    public String analisador() {
        Token t = null;
        int index = 1;
        t = eg.getToken(index);
        String resultadoLexico = "";
        int errosEcontrados = 0;
        while ((t = eg.getToken(index)) != null) {
            if (t.kind == 61) {
                errosEcontrados++;
                resultadoLexico += "Token: " + t.image + " - Linha: " + t.beginLine + " - Coluna: " + t.beginColumn + " - kind:" + t.kind + " - " + getTipoAtributoTokenPorId(t.kind) + "\n";
            }
            if (t.kind == 0) {
                break;
            }


            index++;
        }
        this.outputArea.setText(resultadoLexico);
        
        return "";
    }

    public String analisadorSintatico() {
        List<String> lista = null;
        try {
            lista = new ArrayList<String>();
            eg.Start();
            
            
            if(instrucoesFrame != null)
            	instrucoesFrame.dispose();
            instrucoesFrame = new InstrucoesFrame(eg.analisador.getTabelaDeInstrucoes());
            instrucoesFrame.setVisible(true);
            return ( "Compilado com sucesso");
        } catch (ParseException ex) {
            lista.add(ex.getMessage());
            if(this.instrucoesFrame!= null)
            	this.instrucoesFrame.dispose();
            return ("Erro sintático encontrado\n"+ex.getMessage() + "\n\nCompilação falhou!");
            
	    } catch(RuntimeException e){
	        lista.add(e.getMessage());
            if(this.instrucoesFrame!= null)
            	this.instrucoesFrame.dispose();
            return ("Erro Semântico encontrado\n" + e.getMessage() + " na linha: " + eg.token.beginLine + " coluna: " + eg.token.beginColumn + "\n\nCompilação falhou!");
	    	
	    }

    }


    public String getTipoAtributoTokenPorId(int id) {
        if (id == 54) {
            return "Identificador";
        }
        if (id == 51) {
            return "Constante Inteira";
        }
        if (id == 59) {
            return "Constante Real";
        }
        if (id == 52 || id == 62) {
            return "Constante Literal";
        }
        if (id == 25 || id == 26) {
            return "Constante Lógica";
        }
        if (id >= 6 && id <= 27) {
            return "Palavra Reservada";
        }
        if (id >= 28 && id <= 50) {
            return "Simbolo Especial";
        }
        if (id == 61) {
            return "Erro: Token não reconhecido";
        }
        return "";
    }

    
    
    
    /**
     * 
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaPrincipal2().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoAbrir;
    private javax.swing.JButton botaoColar;
    private javax.swing.JButton botaoCompilar;
    private javax.swing.JButton botaoCopiar;
    private javax.swing.JButton botaoExecutar;
    private javax.swing.JButton botaoNovo;
    private javax.swing.JButton botaoRecortar;
    private javax.swing.JButton botaoSalvar;
    private javax.swing.JLabel coluna;
    private javax.swing.JTextArea inputArea;
    private javax.swing.JMenuItem itemDeMenuAbrir;
    private javax.swing.JMenuItem itemDeMenuColar;
    private javax.swing.JMenuItem itemDeMenuCompilar;
    private javax.swing.JMenuItem itemDeMenuCopiar;
    private javax.swing.JMenuItem itemDeMenuExecutar;
    private javax.swing.JMenuItem itemDeMenuNovo;
    private javax.swing.JMenuItem itemDeMenuRecortar;
    private javax.swing.JMenuItem itemDeMenuSair;
    private javax.swing.JMenuItem itemDeMenuSalvar;
    private javax.swing.JMenuItem itemDeMenuSalvarComo;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel linha;
    private javax.swing.JTextPane outputArea;
    // End of variables declaration//GEN-END:variables
}
